<template>
  <!-- 主容器 -->
  <div class="dashboard-container">
    <!-- 页面头部 -->
    <div class="header">
      <!-- 用户信息展示 -->
      <div class="user-info" v-if="userInfo">
        <p>用户名：{{ userInfo.username }}</p>
        <p>个性签名：{{ userInfo.personalSignature }}</p>
        <p>文章数：{{ userInfo.articleCount }}</p>
        <p>生日：{{ userInfo.birthday }}</p>
        <p>ID：{{ userInfo.id }}</p>
        <p>账号状态：{{ userInfo.accountStatus }}</p>
      </div>
      <!-- 头部操作按钮 -->
      <div class="header-actions">
        <button @click="logout" class="logout-button">退出登录</button>
        <div class="action-buttons">
          <button @click="openUploadArticleModal" class="upload-article-button">上传博客</button>
          <button @click="openModifyInfoModal" class="modify-info-button">修改个人信息</button>
          <button @click="openAppealModal" class="appeal-button">发起申诉</button>
          <button @click="goToProfile" class="profile-button">个人中心</button>
          <button @click="goToChat" class="chat-button">在线聊天</button> <!-- 新增聊天按钮 -->
        </div>
      </div>
    </div>

    <!-- 页面内容 -->
    <div class="content">
      <h1>用户主页</h1>
      
      <!-- 搜索功能部分 -->
      <div class="search-container">
        <input type="text" v-model="searchQuery" placeholder="输入关键词搜索" class="search-input">
        <select v-model="selectedSearchCategory" class="search-select">
          <option value="所有博客">所有博客</option>
          <option value="游戏区">游戏区</option>
          <option value="科技区">科技区</option>
          <option value="体育区">体育区</option>
          <option value="军事区">军事区</option>
          <option value="农业区">农业区</option>
          <option value="艺术区">艺术区</option>
        </select>
        <button @click="searchArticles" class="search-button">搜索</button>
      </div>

      <!-- 分区选择器 -->
      <div class="category-selector">
        <label for="category">选择分区：</label>
        <select id="category" v-model="selectedCategory" @change="fetchUserArticlesByCategory">
          <option value="所有博客">所有博客</option>
          <option value="游戏区">游戏区</option>
          <option value="科技区">科技区</option>
          <option value="体育区">体育区</option>
          <option value="军事区">军事区</option>
          <option value="农业区">农业区</option>
          <option value="艺术区">艺术区</option>
        </select>
      </div>

      <!-- 排序选择器 -->
      <div class="sort-selector">
        <label for="sort">排序方式：</label>
        <select id="sort" v-model="sortOption">
          <option value="publishTime">按发布时间</option>
          <option value="likes">按点赞数</option>
          <option value="comments">按评论数</option>
          <option value="favorites">按收藏数</option>
        </select>
      </div>

      <!-- 文章列表 -->
      <div class="article-list" v-if="sortedAndPagedArticles && sortedAndPagedArticles.length > 0">
        <h2>所有的文章</h2>
        <div class="article-item" v-for="article in sortedAndPagedArticles" :key="article.id">
          <h3>{{ article.title }}</h3>
          <div class="article-meta">
            <span>分区：{{ article.category }}</span>
            <span>作者：{{ article.writer }}</span>
            <span>发布时间：{{ article.publishTime }}</span>
            <span>点赞数：{{ article.like }}</span>
            <span>评论数：{{ article.comment }}</span>
            <span>收藏数：{{ article.favorite }}</span>
          </div>
          <button @click="viewArticle(article)" class="view-button">查看内容</button>
        </div>

        <!-- 分页查询 -->
        <div class="pagination">
          <button :disabled="currentPage === 1" @click="prevPage" class="pagination-button">上一页</button>
          <span class="page-info">第 {{ currentPage }} 页，共 {{ totalPages }} 页</span>
          <button :disabled="currentPage === totalPages" @click="nextPage" class="pagination-button">下一页</button>
        </div>
      </div>
      <div v-else>
        <p>暂无文章</p>
      </div>
    </div>
    
    <!-- 修改个人信息弹窗 -->
    <div v-if="showModifyInfoModal" class="modal">
      <div class="modal-content">
        <span class="close-button" @click="closeModifyInfoModal">&times;</span>
        <h2>修改个人信息</h2>
        <div class="form-group">
          <label for="signature">个性签名：</label>
          <input type="text" id="signature" v-model="modifyInfo.personalSignature" />
        </div>
        <div class="form-group">
          <label for="birthday">生日：</label>
          <input type="date" id="birthday" v-model="modifyInfo.birthday" />
        </div>
        <div class="modal-actions">
          <button @click="confirmModifyInfo" class="confirm-button">确认更改</button>
          <button @click="closeModifyInfoModal" class="cancel-button">取消</button>
        </div>
      </div>
    </div>

    <!-- 上传博客弹窗 -->
    <div v-if="showUploadArticleModal" class="modal">
      <div class="modal-content">
        <span class="close-button" @click="closeUploadArticleModal">&times;</span>
        <h2>上传博客</h2>
        <div class="form-group">
          <label for="article-title">文章题目：</label>
          <input type="text" id="article-title" v-model="articleForm.title" />
        </div>
        <div class="form-group">
          <label for="article-content">文章内容：</label>
          <textarea id="article-content" v-model="articleForm.content"></textarea>
        </div>
        <div class="form-group">
          <label for="article-category">文章分区：</label>
          <select id="article-category" v-model="articleForm.category">
            <option value="游戏区">游戏区</option>
            <option value="科技区">科技区</option>
            <option value="体育区">体育区</option>
            <option value="军事区">军事区</option>
            <option value="农业区">农业区</option>
            <option value="艺术区">艺术区</option>
          </select>
        </div>
        <div class="form-group">
          <label>发布选项：</label>
          <div>
            <input type="radio" id="immediate" value="immediate" v-model="articleForm.publishOption" />
            <label for="immediate">即时发布</label>
            <input type="radio" id="scheduled" value="scheduled" v-model="articleForm.publishOption" />
            <label for="scheduled">定时发布</label>
          </div>
          <div v-if="articleForm.publishOption === 'scheduled'">
            <label for="scheduled-date">选择发布日期：</label>
            <input type="date" id="scheduled-date" v-model="articleForm.scheduledDate" :min="today" />
          </div>
        </div>
        <div class="modal-actions">
          <button @click="confirmUploadArticle" class="confirm-button">发布</button>
          <button @click="closeUploadArticleModal" class="cancel-button">取消</button>
        </div>
      </div>
    </div>

    <!-- 申诉弹窗 -->
    <div v-if="showAppealModal" class="modal">
      <div class="modal-content">
        <span class="close-button" @click="closeAppealModal">&times;</span>
        <h2>发起申诉</h2>
        <div class="form-group">
          <label>申诉对象：</label>
          <select v-model="appealForm.appealTarget">
            <option value="系统">系统管理员</option>
            <option value="游戏区">游戏区</option>
            <option value="科技区">科技区</option>
            <option value="军事区">军事区</option>
            <option value="农业区">农业区</option>
            <option value="体育区">体育区</option>
            <option value="艺术区">艺术区</option>
          </select>
        </div>
        <div class="form-group">
          <label for="appeal-content">申诉内容：</label>
          <textarea id="appeal-content" v-model="appealForm.content"></textarea>
        </div>
        <div class="modal-actions">
          <button @click="submitAppeal" class="confirm-button">上传申诉</button>
          <button @click="closeAppealModal" class="cancel-button">取消</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue';
import { useRouter } from 'vue-router';

export default defineComponent({
  data() {
    return {
      userInfo: null, // 用户信息
      articles: [], // 文章列表
      showModifyInfoModal: false, // 修改信息弹窗显示状态
      showUploadArticleModal: false, // 上传博客弹窗显示状态
      showAppealModal: false, // 申诉弹窗显示状态
      modifyInfo: {
        personalSignature: '',
        birthday: ''
      }, // 修改的用户信息
      articleForm: {
        title: '',
        content: '',
        category: '游戏区',
        publishOption: 'immediate', // 默认为即时发布
        scheduledDate: '' // 定时发布的日期
      }, // 新博客表单数据
      appealForm: {
        appealTarget: '系统管理员',
        content: ''
      }, // 申诉表单数据
      selectedCategory: '所有博客', // 当前选择的分区
      currentPage: 1, // 当前页码
      pageSize: 5, // 每页显示的文章数
      searchQuery: '', // 搜索功能
      selectedSearchCategory: '所有博客', // 搜索功能的新字段
      sortOption: 'publishTime', // 排序选项，默认按发布时间排序
      today: new Date().toISOString().split('T')[0] // 当前日期，用于限制日期选择器
    };
  },
  setup() {
    const router = useRouter();
    return { router };
  },
  computed: {
    // 总页数计算
    totalPages() {
      return Math.ceil(this.articles.length / this.pageSize);
    },
    // 对所有文章进行排序
    sortedArticles() {
      const articlesCopy = JSON.parse(JSON.stringify(this.articles)); // 创建一个副本，避免修改原始数据
      return articlesCopy.sort((a, b) => {
        if (this.sortOption === 'publishTime') {
          return new Date(b.publishTime) - new Date(a.publishTime); 
        } else if (this.sortOption === 'likes') {
          return b.like - a.like; 
        } else if (this.sortOption === 'comments') {
          return b.comment - a.comment;
        } else if (this.sortOption === 'favorites') {
          return b.favorite - a.favorite;
        }
        return 0;
      });
    },
    // 对排序后的文章进行分页
    sortedAndPagedArticles() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.sortedArticles.slice(start, end);
    }
  },
  created() {
    this.fetchUserInfo(); // 获取用户信息
    this.fetchUserArticlesByCategory(); // 获取文章列表
  },
  methods: {
    // 获取用户信息
    async fetchUserInfo() {
      const token = localStorage.getItem('token');
      const username = localStorage.getItem('username');
      if (!token || !username) {
        this.router.push('/');
        return;
      }

      try {
        const response = await fetch(`http://localhost:8080/lzl_content2_war_exploded/userInformation?username=${username}`, {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${token}`
          }
        });

        const data = await response.json();

        if (response.ok) {
          this.userInfo = data;
          localStorage.setItem('userInfo', JSON.stringify(data));
          // 初始化修改信息
          this.modifyInfo.personalSignature = data.personalSignature;
          this.modifyInfo.birthday = data.birthday;
        } else {
          alert('获取用户信息失败！');
          this.router.push('/');
        }
      } catch (error) {
        console.error('Error fetching user info:', error);
        alert('获取用户信息时出错！');
        this.router.push('/');
      }
    },
    // 根据分区获取文章列表
    async fetchUserArticlesByCategory() {
      const token = localStorage.getItem('token');
      const username = localStorage.getItem('username');
      const category = this.selectedCategory; // 获取当前选择的分区
      if (!token || !username) {
        return;
      }

      try {
        const response = await fetch(`http://localhost:8080/lzl_content2_war_exploded/userArticlePrint?username=${username}&category=${category}`, {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${token}`
          }
        });

        const data = await response.json();

        if (response.ok) {
          this.articles = data;
          this.currentPage = 1; // 重置到第一页
        } else {
          alert('获取文章信息失败！');
        }
      } catch (error) {
        console.error('Error fetching user articles:', error);
        alert('获取文章信息时出错！');
      }
    },
    // 搜索功能按钮方法
    async searchArticles() {
      if (!this.searchQuery.trim()) {
        alert('请输入搜索关键词');
        return;
      }

      const token = localStorage.getItem('token');
      const username = localStorage.getItem('username');
      const searchQuery = this.searchQuery;
      const category = this.selectedSearchCategory;
      if (!token || !username) {
        return;
      }

      try {
        const response = await fetch(`http://localhost:8080/lzl_content2_war_exploded/userArticleSelect?query=${encodeURIComponent(searchQuery)}&category=${encodeURIComponent(category)}`, {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${token}`
          }
        });

        const data = await response.json();

        if (response.ok) {
          // 过滤匹配搜索条件的文章
          this.articles = data;
          this.currentPage = 1; // 搜索结果匹配的重置
        } else {
          alert('搜索文章失败！');
        }
      } catch (error) {
        console.error('Error searching articles:', error);
        alert('搜索文章时出错！');
      }
    },
    // 退出登录
    logout() {
      localStorage.removeItem('token');
      localStorage.removeItem('userInfo');
      localStorage.removeItem('username');
      localStorage.removeItem('loginType');
      this.router.push('/');
    },
    // 查看文章详情
    async viewArticle(article) {
      const token = localStorage.getItem('token');
      const username = localStorage.getItem('username');
      if (!token || !username) {
        this.router.push('/');
        return;
      }

      // 发送文章浏览信息到后端
      try {
        const response = await fetch(`http://localhost:8080/lzl_content2_war_exploded/userBrowsedArticle`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${token}`
          },
          body: JSON.stringify({
            writer: article.writer,
            title: article.title,
            category: article.category,
            currentUsername: username
          })
        });

        if (!response.ok) {
          console.error('Error recording article browse:', response.statusText);
        }
      } catch (error) {
        console.error('Error recording article browse:', error);
      }

      // 跳转到文章详情页
      this.router.push({
        name: 'article',
        query: { article: JSON.stringify(article) }
      });
    },
    // 打开修改信息弹窗
    openModifyInfoModal() {
      this.showModifyInfoModal = true;
    },
    // 关闭修改信息弹窗
    closeModifyInfoModal() {
      this.showModifyInfoModal = false;
    },
    // 打开上传博客弹窗
    openUploadArticleModal() {
      this.showUploadArticleModal = true;
    },
    // 关闭上传博客弹窗
    closeUploadArticleModal() {
      this.showUploadArticleModal = false;
    },
    // 打开申诉弹窗
    openAppealModal() {
      this.showAppealModal = true;
    },
    // 关闭申诉弹窗
    closeAppealModal() {
      this.showAppealModal = false;
    },
    // 确认修改个人信息
    async confirmModifyInfo() {
      const token = localStorage.getItem('token');
      const username = localStorage.getItem('username');
      if (!token || !username) {
        return;
      }

      try {
        const response = await fetch(`http://localhost:8080/lzl_content2_war_exploded/userModifyInformation`, {
          method: 'PUT',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${token}`
          },
          body: JSON.stringify({
            username: username,
            personalSignature: this.modifyInfo.personalSignature,
            birthday: this.modifyInfo.birthday
          })
        });

        if (response.ok) {
          alert('修改成功！');
          this.fetchUserInfo(); // 刷新用户信息
          this.closeModifyInfoModal();
        } else {
          alert('修改失败！');
        }
      } catch (error) {
        console.error('Error modifying user info:', error);
        alert('修改用户信息时出错！');
      }
    },
    // 确认上传博客
    async confirmUploadArticle() {
      const token = localStorage.getItem('token');
      const username = localStorage.getItem('username');
      if (!token || !username) {
        return;
      }

      let publishTime;

      if (this.articleForm.publishOption === 'immediate') {
        publishTime = new Date().toISOString().split('T')[0]; // 获取当前日期
      } else {
        publishTime = this.articleForm.scheduledDate; // 使用用户选择的定时发布日期
      }

      try {
        const response = await fetch(`http://localhost:8080/lzl_content2_war_exploded/userUploadArticle`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${token}`
          },
          body: JSON.stringify({
            username: username,
            title: this.articleForm.title,
            content: this.articleForm.content,
            category: this.articleForm.category,
            publishTime: publishTime
          })
        });

        if (response.ok) {
          alert('文章上传成功！');
          this.closeUploadArticleModal();
          this.articleForm.title = '';
          this.articleForm.content = '';
          this.articleForm.category = '游戏区';
          this.articleForm.publishOption = 'immediate'; // 重置发布选项
          this.articleForm.scheduledDate = ''; // 重置定时发布日期
          this.fetchUserArticlesByCategory(); // 刷新文章列表
        } else {
          alert('文章上传失败，请检查是否被禁用，可以通过申诉解除禁用');
        }
      } catch (error) {
        console.error('Error uploading article:', error);
        alert('上传文章时出错！');
      }
    },
    // 提交申诉
    async submitAppeal() {
      const token = localStorage.getItem('token');
      const username = localStorage.getItem('username');
      if (!token || !username) {
        return;
      }

      if (!this.appealForm.content.trim()) {
        alert('请输入申诉内容');
        return;
      }

      try {
        const response = await fetch(`http://localhost:8080/lzl_content2_war_exploded/userAppeal`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${token}`
          },
          body: JSON.stringify({
            username: username,
            appealTarget: this.appealForm.appealTarget,
            content: this.appealForm.content
          })
        });

        if (response.ok) {
          alert('申诉成功，请耐心等待！');
          this.closeAppealModal();
          this.appealForm.appealTarget = '系统管理员';
          this.appealForm.content = '';
        } else {
          alert('申诉失败！');
        }
      } catch (error) {
        console.error('Error submitting appeal:', error);
        alert('申诉时出错！');
      }
    },
    // 跳转到个人中心
    goToProfile() {
      this.router.push('/profile');
    },
    // 新增方法：跳转到聊天页面
    goToChat() {
      this.router.push('/chat');
    },
    // 上一页按钮点击事件
    prevPage() {
      if (this.currentPage > 1) {
        this.currentPage--;
      }
    },
    // 下一页按钮点击事件
    nextPage() {
      if (this.currentPage < this.totalPages) {
        this.currentPage++;
      }
    }
  }
});
</script>

<style scoped>
.dashboard-container {
  font-family: Arial, sans-serif;
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 0;
  border-bottom: 1px solid #eee;
  margin-bottom: 20px;
}

.user-info {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.user-info p {
  margin: 5px 0;
}

.header-actions {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.logout-button {
  background-color: #4CAF50;
  color: white;
  border: none;
  padding: 10px 15px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.logout-button:hover {
  background-color: #45a049;
}

.action-buttons {
  display: flex;
  gap: 10px;
  margin-top: 10px;
}

.upload-article-button {
  background-color: #ff9800;
  color: white;
  border: none;
  padding: 10px 15px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.upload-article-button:hover {
  background-color: #e68a00;
}

.modify-info-button {
  background-color: #2196F3;
  color: white;
  border: none;
  padding: 10px 15px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.modify-info-button:hover {
  background-color: #0b7dda;
}

.appeal-button {
  background-color: #9C27B0;
  color: white;
  border: none;
  padding: 10px 15px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.appeal-button:hover {
  background-color: #7B1FA2;
}

.profile-button {
  background-color: #607D8B;
  color: white;
  border: none;
  padding: 10px 15px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.profile-button:hover {
  background-color: #455A64;
}

.chat-button {
  background-color: #00bcd4;
  color: white;
  border: none;
  padding: 10px 15px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.chat-button:hover {
  background-color: #0097a7;
}

.content {
  padding: 20px 0;
}

h1 {
  color: #333;
  margin: 0 0 20px 0;
}

.search-container {
  display: flex;
  margin-bottom: 20px;
}

.search-input {
  flex: 3;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  margin-right: 10px;
}

.search-select {
  flex: 1;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  margin-right: 10px;
}

.search-button {
  padding: 8px 15px;
  background-color: #2196F3;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.category-selector {
  margin-bottom: 20px;
}

.category-selector label {
  display: inline-block;
  margin-right: 10px;
}

.category-selector select {
  padding: 8px;
  border-radius: 4px;
  border: 1px solid #ddd;
}

.sort-selector {
  margin-bottom: 20px;
}

.sort-selector label {
  display: inline-block;
  margin-right: 10px;
}

.sort-selector select {
  padding: 8px;
  border-radius: 4px;
  border: 1px solid #ddd;
}

.article-list {
  margin-top: 20px;
}

.article-item {
  border: 1px solid #eee;
  padding: 15px;
  margin-bottom: 15px;
  border-radius: 5px;
  background-color: #f9f9f9;
}

.article-item h3 {
  margin-top: 0;
  color: #333;
}

.article-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  margin: 10px 0;
  color: #666;
}

.article-meta span {
  white-space: nowrap;
}

.view-button {
  background-color: #2196F3;
  color: white;
  border: none;
  padding: 6px 12px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
  margin-left: auto;
}

.view-button:hover {
  background-color: #0b7dda;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 20px;
}

.pagination-button {
  background-color: #2196F3;
  color: white;
  border: none;
  padding: 8px 15px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
  margin: 0 10px;
}

.pagination-button:hover {
  background-color: #0b7dda;
}

.pagination-button:disabled {
  background-color: #f1f1f1;
  color: #999;
  cursor: not-allowed;
}

.page-info {
  margin: 0 10px;
  color: #666;
}

.modal {
  display: flex;
  justify-content: center;
  align-items: center;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 1000;
}

.modal-content {
  background-color: white;
  padding: 20px;
  border-radius: 5px;
  max-width: 500px;
  width: 100%;
  position: relative;
}

.close-button {
  position: absolute;
  top: 10px;
  right: 15px;
  font-size: 24px;
  cursor: pointer;
}

.form-group {
  margin-bottom: 15px;
}

label {
  display: block;
  margin-bottom: 5px;
  color: #333;
}

input, textarea, select {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

textarea {
  height: 150px;
}

.modal-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}

.confirm-button {
  background-color: #2196F3;
  color: white;
  border: none;
  padding: 8px 15px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.confirm-button:hover {
  background-color: #0b7dda;
}

.cancel-button {
  background-color: #f1f1f1;
  color: #333;
  border: none;
  padding: 8px 15px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.cancel-button:hover {
  background-color: #e1e1e1;
}
</style>